<?php
namespace app\modules\weixin\controllers;


use \app\common\components\BaseWebController;
use \app\common\services\UtilService;
use \app\common\services\UrlService;
use Yii;
use yii\log\FileTarget;
use \app\models\book\Book;
class MsgController extends BaseWebController
{
	
	public function actionIndex(){
		$path=UtilService::getRootPath().'/0.log';
		file_put_contents($path,serialize($_GET),FILE_APPEND);
		$res=unserialize(file_get_contents($path)) ;
		$_GET=$res;

		if(!$this->checkSignature()){
			return "failed checkSignature";
		}

		//微信第一次验证
		if(array_key_exists("echostr", $_GET) && $_GET['echostr']){
			// return $_GET['echostr'];
		}
		//获取post的xml数据
		// var_dump($_POST);
		$xml_data=file_get_contents("php://input");
		$this->record_log( "[xml_data]:". $xml_data );
		
		if(!$xml_data){
			return "error xml";
		}
		
		$xml_obj=simplexml_load_string($xml_data,"SimpleXMLElement",LIBXML_NOCDATA);
		$toUser=$xml_obj->ToUserName;
		$fromUser=$xml_obj->FromUserName;
		$msgType=$xml_obj->MsgType;
		$res=['type'=>'text','data'=>$this->defaultTpl()];
		switch($msgType){
			case"text":
				$kw=trim($xml_obj->Content);
				$res=$this->search($kw);
				break;
			case"event":
				
				break;
		}
		switch($res['type']){
			case"text":
				return $this->textTpl($toUser,$fromUser,$res['data']);
				break;
			case"rich":
				
				return $this->richTpl($toUser,$fromUser,$res['data']);
				break;
		}
		return "hello world";
	}
	//查找方法
	public function search($kw){
		$query=Book::find()->where(['status'=>1]);
		$where_name=['LIKE','name','%'.$kw.'%',false];
		$where_tag=['LIKE','tags','%'.$kw.'%',false];
		$query->andWhere(["OR",$where_name,$where_tag]);
		$res=$query->orderBy(['id'=>SORT_DESC])->limit(3)->all();
		$data=$res?$this->getRichXml($res):$this->defaultTpl();
		$type=$res?"rich":"text";
		return ["type"=>$type,"data"=>$data];

	}
	//文本消息
	public function textTpl($toUser,$fromUser,$content){
		$textTpl=<<<XML
<xml>  
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>  
<CreateTime>%s</CreateTime>  
<MsgType><![CDATA[%s]]></MsgType>  
<Content><![CDATA[%s]]></Content>
</xml>
XML;
		return sprintf($textTpl,$fromUser,$toUser,time(),'text',$content);
	}
	//默认没有找到的
	public function defaultTpl(){
		$textTpl=<<<XML
没有找到你想要的东西:(
XML;
		return $textTpl;
	}
	//富文本
	private function richTpl( $toUser ,$fromUser,$content){
		// var_dump($content);
		$tpl = <<<EOT
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
%s
</xml>
EOT;
		return sprintf($tpl, $fromUser, $toUser, time(), $content);
	}

	private function getRichXml( $list ){
		// var_dump($list);
		$article_count = count( $list );
		$article_content = "";
		foreach($list as $_item){
			$tmp_description = $_item['summary'];
			$tmp_pic_url = UrlService::buildPicUrl( "book",$_item['main_image'] );
			// echo $tmp_pic_url;
			$tmp_url = UrlService::buildMUrl( "/product/info",[ 'id' => $_item['id'] ] );
			$article_content .= "
<item>
<Title><![CDATA[{$_item['name']}]]></Title>
<Description><![CDATA[{$tmp_description}]]></Description>
<PicUrl><![CDATA[{$tmp_pic_url}]]></PicUrl>
<Url><![CDATA[{$tmp_url}]]></Url>
</item>";
		}

		$article_body = "<ArticleCount>%s</ArticleCount>
<Articles>
%s
</Articles>";
		return sprintf($article_body,$article_count,$article_content);
	}
	public function checkSignature()
	{
	    $signature=$this->get("signature","");
	    // echo $signature;
	    $timestamp=$this->get("timestamp","");
	    
	    $nonce=$this->get("nonce","");
		$tmpArr =array(\Yii::$app->params['weixin']['token'],$timestamp,$nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		// echo $signature."</br>".$tmpStr;
		if( $signature==$tmpStr ){
			return true;
		}else{
			return false;
		}
	}
	//xml记录
	public function record_log($msg){
		$log = new FileTarget();
		$log->logFile = Yii::$app->getRuntimePath() . "/logs/weixin_msg_".date("Ymd").".log";
		$request_uri = isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:'';
		$log->messages[] = [
			"[url:{$request_uri}][post:".http_build_query($_POST)."] [msg:{$msg}]",
			1,
			'application',
			microtime(true)
		];
		$log->export();
	}
}
?>